package org.rcy.ruicingmarket.security;

import org.rcy.framework.api.security.SecurityUser;
import org.rcy.framework.api.security.UserPrincipal;
import org.rcy.framework.security.principal.UserProvider;
import org.rcy.ruicingmarket.resource.ResourceGroupDao;
import org.rcy.ruicingmarket.oss.role.RoleDao;
import org.rcy.ruicingmarket.oss.user.OssUserDao;
import org.rcy.ruicingmarket.resource.ResourceGroup;
import org.rcy.ruicingmarket.oss.role.Role;
import org.rcy.ruicingmarket.oss.user.OssUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/11/1 11:23
 */

@Component
public class OssUserProvider implements UserProvider<String> {
	@Autowired
	private OssUserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private ResourceGroupDao resourceGroupDao;

	@Override
	public SecurityUser loadUser(String s) {
		OssUser user = userDao.findByAccount(s);
		if(user == null) {
			return null;
		}
		List<Role> roles = roleDao.getRolesByUserId(user.getId());
		if(!roles.isEmpty()){
			Set<Role> ossRoles = new HashSet<>();
			ossRoles.addAll(roles);
			user.setOssRoles(ossRoles);
			List<Long> rolesIds = roles.stream().map(role -> role.getId()).collect(Collectors.toList());
			Set<ResourceGroup> resourceGroups = resourceGroupDao.getResourceGroupsByRoles(rolesIds).size()> 0 ? null : resourceGroupDao.getResourceGroupsByRoles(rolesIds).stream().collect(Collectors.toSet());
			user.setResourceGroups(resourceGroups);
		}
		return user;
	}

	@Override
	public UserPrincipal postLoadUser(SecurityUser securityUser) {
		return securityUser;
	}
}
